<template>
	<div class="totalStyle contractinfo_box">
		<div class="tablestyle">
			<div class="titleStyle">
				<p class="leftTitle font_w">拖轮计费</p>
				<div>
					<el-button type="primary" :loading="exportLoading" @click="handleExport">导出数据</el-button>
					<el-button v-if="userInfo&&(userInfo.roleId == 52 || userInfo.roleId == 10)" type="primary" :disabled="applyBtnStatus" @click="handleAudit(2)">完成缴费</el-button>
					<el-button v-if="userInfo&&(userInfo.roleId == 52 || userInfo.roleId == 10)" type="primary" :disabled="unApplyBtnStatus" @click="handleAudit(1)">批量反缴费</el-button>
				</div>
			</div>
			<div class="bottomBox">
				<div class="searchsize">
					<el-row :gutter="24" style="width: 100%;" class="searchBox flex">
						<el-col :span="7.5">
							<el-date-picker v-model="planTime" type="daterange" start-placeholder="开始日期"
								end-placeholder="结束日期" value-format="YYYY-MM-DD" :clearable="false" />
						</el-col>
						<el-col :span="3">
							<el-input v-model="queryParams.planCode" placeholder="请输入计划编号" clearable />
						</el-col>
						<el-col :span="3">
							<el-input v-model="queryParams.shipName" placeholder="请输入船名" clearable />
						</el-col>
						<!-- <el-col :span="3">
							<Select placeholder="请选择作业港区"
								:dataConfig="{ params: { type: 'DICT',dictType:'PORT_AREA' } }" disabled
								v-model:value="queryParams.notionCode" v-model:label="queryParams.nationName" />
						</el-col> -->
						<el-col :span="3">
							<Select placeholder="请选择拖轮" :selectData="selects.tugList" v-model:value="queryParams.tugId"
								v-model:label="queryParams.tugNo" />
						</el-col>
						<el-col :span="4">
							<el-button type="info" plain @click="reset">重置</el-button>
							<el-button type="primary" plain class="searchbutton" @click="search">查询</el-button>
						</el-col>
					</el-row>
				</div>
				<div class="chartstyle">
					<el-table :data="tableData" row-key="id" :expand-row-keys="expandRowKeys"
						:header-cell-style="{ background: '#F2F5FA' }" border style="width: 100%;"
						@selection-change="handleSelectionChange" @select-all="handleSelectionChange"
						:summary-method="getSummaries" show-summary>
						<el-table-column type="selection" :width="60" align="center" />
						<el-table-column type="index" :index="1" label="序号" :width="60" align="center" />
						<el-table-column type="expand" label="作业记录" :width="100">
							<template #default="props">
								<el-table :data="props.row.children" :header-cell-style="{ background: '#F2F5FA' }"
									border style="width: 100%;">
									<el-table-column prop="tugNo" label="拖轮编号" :width="120" />
									<el-table-column prop="workItemName" label="作业项目" :width="120" />
									<el-table-column prop="amount" label="费用" :width="120" />
									<el-table-column prop="calculateRemark" label="费用备注" :width="200" />
									<el-table-column prop="beginTime" label="开始作业时间" :width="150" />
									<el-table-column prop="endTime" label="结束作业时间" :width="150" />
									<el-table-column prop="workHours" label="作业时长(h)" :width="100" />
									<el-table-column label="操作列" width="120" align="center">
										<template #default="scope">
											<span class="buttonFun cursor" @click="viewRecord(scope.row)">查看</span>
										</template>
									</el-table-column>
									<template #empty>
										<el-empty v-loading="tableLoading"></el-empty>
									</template>
								</el-table>
							</template>
						</el-table-column>

						<el-table-column prop="planTime" label="计划作业时间" :width="150" />
						<el-table-column prop="planCode" label="计划编号" :width="150" />
						<el-table-column label="船名-航次" :width="120">
							<template #default="scope">
								{{scope.row.shipName + '-' + scope.row.voyage}}
							</template>
						</el-table-column>
						<el-table-column prop="fee" label="总费用" :width="120" align="center" />
						<el-table-column prop="calculateRemark" label="费用备注" :width="250" />
						<el-table-column prop="berthNo" label="泊位" :width="80" />
						<el-table-column label="贸别" :width="80">
							<template #default="scope">
								<el-tag
									:type="scope.row.tradeType === 'N' ? 'success' : 'warning'">{{scope.row.tradeType === 'N' ? '内贸' : '外贸'}}</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="进出港" :width="80">
							<template #default="scope">
								<el-tag
									:type="scope.row.inOut === 'J' ? 'success' : 'warning'">{{scope.row.inOut === 'J' ? '进' : '出'}}</el-tag>
							</template>
						</el-table-column>
						<!-- <el-table-column label="装卸" :width="80">
							<template #default="scope">
								<el-tag
									:type="scope.row.loadUnload === 'Z' ? 'success' : 'warning'">{{scope.row.loadUnload === 'Z' ? '装' : '卸'}}</el-tag>
							</template>
						</el-table-column> -->
						<el-table-column prop="customerName" label="客户名称" :width="120" />
						<!-- <el-table-column prop="cargoName" label="货名" :width="120" />
						<el-table-column prop="portAreaName" label="作业港区" :width="100" />
						<el-table-column prop="dockName" label="作业码头" :width="100" />
						<el-table-column prop="frontDraft" label="前吃水" :width="100" />
						<el-table-column prop="rearDraft" label="后吃水" :width="100" />
						<el-table-column prop="ton" label="货重" :width="100" /> -->
						<el-table-column label="计费审核状态" :width="100" fixed="right" align="center">
							<template #default="scope">
								<el-tag
									:type="scope.row.status == 1 ? 'warning' : scope.row.status == 3 ? 'primary' : scope.row.status == 2 ? 'success' : ''">{{scope.row.status == 1 ? '未完工' : scope.row.status == 3 ? '完工' :  scope.row.status == 2 ? '已审核' : ''}}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="remark" label="备注" :width="200" />
						<template #empty>
							<el-empty v-loading="tableLoading"></el-empty>
						</template>
					</el-table>
					<div class="demo-pagination-block">
						<el-pagination :current-page="queryParams.startPage" :page-size="queryParams.pageSize"
							:page-sizes="[5, 10, 15, 20]" :background="background"
							layout="total, sizes, prev, pager, next, jumper" :total="total"
							@size-change="handleSizeChange" @current-change="handleCurrentChange" />
					</div>
					<el-row style="position: absolute;bottom: 32px;padding-left: 12px;width: 50%;">
					  <el-col>当前日期范围内总费用：{{totalMoney}}</el-col>
					</el-row>
				</div>
			</div>
		</div>

		<!-- 详情 -->
		<Detail ref="detailRef" @callback="queryTableData(queryParams)"></Detail>
	</div>
</template>

<script setup name="plan">
	import Select from '@/components/Select/index.vue';
	import tugApi from '@/api/basicData/tug';
	import api from '@/api/plan/plan/index';
	import recordApi from '@/api/plan/plan/recordIndex'
	import Detail from './component/detail.vue';
	import { exportFile } from "@/utils/fileUtils";
	import {
		getNowDate
	} from '@/utils/index'
	import {
		ref,
		onMounted,
		computed
	} from "vue";
	import {
		ElMessage,
		ElMessageBox,
		ElNotification
	} from "element-plus";
	const userInfo = ref()
	const applyBtnStatus = computed(() => selectRows.value.length < 1 || (selectRows.value.length >= 1 && (selectRows.value.map(v => v.status).indexOf(1) > -1 || selectRows.value.map(v => v.status).indexOf(2) > -1)))
	const unApplyBtnStatus = computed(() => selectRows.value.length < 1 || (selectRows.value.length >= 1 && (selectRows.value.map(v => v.status).indexOf(1) > -1 || selectRows.value.map(v => v.status).indexOf(3) > -1)))
	const selectRows = ref([])
	const detailRef = ref(null) // 明细组件ref
	const tableLoading = ref(false)
	const total = ref(0)
	const totalMoney = ref(0)
	const tableData = ref()
	const selects = ref({
		tugList: []
	})
	const planTime = ref([getNowDate('YYYY-MM') + '-01', getNowDate('YYYY-MM') + '-' + new Date(new Date(new Date()
			.getFullYear(), new Date().getMonth() + 1, 1) - 1).getDate()])
	const queryParams = ref({
		planCode: '',
		shipName: '',
		notionCode: '04',
		nationName: '',
		portAreaCode:'04',
		portAreaName:'',
		planTimeStart: '',
		planTimeEnd: '',
		tugId: '',
		tugNo: '',
		isFinishWork:'',
		startPage: 1,
		pageSize: 10
	})
	//列表复选框选择事件
	const handleSelectionChange = (e) => {
		// 在这里处理选中项，不包括展开行
		// 通过判断selection中的item是否包含type='expand'的column来过滤
		const nonExpandRows = tableData.value.filter(item => {
			return e.includes(item); // 假设item不是展开行的数据
		});

		selectRows.value = nonExpandRows

	}
	//重置
	const reset = () => {
		queryParams.value = {
			planCode: '',
			shipName: '',
			notionCode: '04',
			nationName: '',
			portAreaCode:'04',
			portAreaName:'',
			planTimeStart: '',
			planTimeEnd: '',
			tugId: '',
			tugNo: '',
			isFinishWork:'',
			startPage: 1,
			pageSize: 10
		}
		queryTableData(queryParams.value)
	}
	//审核事件
	const handleAudit = (status) => {
		if (selectRows.value&&selectRows.value.length == 0) {
			ElMessage.error('请选择至少一条数据')
			return
		}
		var str = '审核成功后作业记录不能进行完工操作，确定审核当前数据？'
		if (status == 1) {
			str = '确定将选中的计划进行反缴费？'
		}
		ElMessageBox.confirm(str, "确定", {
			type: "warning",
			icon: 'WarningFilled'
		}).then(_ => {
			var data = {
				ids: [],
				status: status
			};
			if (selectRows.value&&selectRows.value.length > 0) {
				data.ids = selectRows.value.map(v => v.id)
			}
			api.approveBatch(data).then(res => {
				if (res.code === 200) {
					ElMessage.success('审核成功')
					queryTableData(queryParams.value)
				} else {
					ElMessage.error(res.msg)
				}
			})
		}).catch(_ => {
			console.log("取消审核");
		})
	}
	//查看事件
	const viewRecord = row => {
		detailRef.value.show({
			mode: 'view',
			row: row
		})
	}
	//切换一页显示多少条数据
	const handleSizeChange = (val) => {
		queryParams.value.pageSize = val;
		queryTableData(queryParams.value);
	};
	// 点击跳转到第几页
	const handleCurrentChange = (val) => {
		queryParams.value.startPage = val;
		queryTableData(queryParams.value);
	};
	//查询
	const search = () => {
		queryParams.value.startPage = 1
		queryParams.value.pageSize = 10
		queryTableData(queryParams.value)
	}
	const expandRowKeys = ref([])
	const footerData = ref([])
	//查询
	const queryTableData = (e) => {
		tableLoading.value = true
		if(planTime.value&&planTime.value.length > 0){
			e.planTimeStart = planTime.value[0]
			e.planTimeEnd = planTime.value[1]
		}
		e.queryType = 1
		queryParams.value = e
		api.getList(queryParams.value).then(res => {
			tableLoading.value = false
			tableData.value = res.data?.records || []
			total.value = res.data?.total || 0
			if (total.value > 0) {
				expandRowKeys.value = [tableData.value[0].id]
			}
		}).then(_ => {
			if (tableData.value&&tableData.value.length > 0) {
				var totalNum = 0;
				tableData.value.forEach(item => {
					totalNum += parseFloat(item.fee)
				})
				footerData.value = [{
					shipName: '当前页合计',
					fee: totalNum,
				}]
			} else {
				footerData.value = []
			}
		})
		api.totalAmount(e).then(res => {
			totalMoney.value = res.data.value
		})
	}
	const getSummaries = (param) => {
		const {
			columns,
			data
		} = param
		const sums = []
		columns.forEach((column, index) => {
			if (index === 0) {
				sums[index] = '合计'
				return
			} else if (index === 6) {
				if (tableData.value&&tableData.value.length > 0) {
					var totalNum = 0;
					tableData.value.forEach(item => {
						totalNum += parseFloat(item.fee)
					})
					sums[index] = totalNum
				}
			} else {
				sums[index] = ""
			}
		})
		return sums
	}

	const getSelectList = () => {
		selects.value.tugList = []
		tugApi.getList({
			startPage: 1,
			pageSize: 100,
			portAreaCode:'04'
		}).then(res => {
			if (res.data.records.length > 0) {
				var par = {}
				res.data.records.forEach(item => {
					par = {
						label: item.tugNo,
						value: item.id
					}
					selects.value.tugList.push(par)
				})
			}
		})
	}
	onMounted(() => {
		getSelectList()
		queryTableData(queryParams.value)
		userInfo.value = JSON.parse(localStorage.getItem('userData'))
	})
	
	// 导出数据
	const exportLoading = ref(false)
	const handleExport = () => {
		exportLoading.value = true;
		var params = JSON.parse(JSON.stringify(queryParams.value))
		params.pageSize = 1000
		recordApi.exportTugFee(params).then(res=>{
			exportFile(res.data,'拖轮计费导出','xlsx')
		}).then(_=>{
			setTimeout(function(){
				exportLoading.value = false;
			},300)
		})
	}
</script>
<style lang='less' scoped>
	.tablestyle {
		position: relative;

		.inputBox {
			:deep(.el-input) {
				width: 200px;
			}
		}

		:deep(.el-table__header thead tr) {
			background-color: rgba(64, 158, 255, 0.1);
		}

		:deep(.el-col-3) {
			max-width: none;
		}
	}

	.contractinfo_box {
		:deep(.el-table--fit) {
			height: 100%;
		}

		:deep(.el-table__body-wrapper) {
			overflow-y: auto;
		}

		.tablestyle {
			position: relative;

			:deep(.el-table__header thead tr) {
				background-color: rgba(64, 158, 255, 0.1);
			}

			:deep(.el-col-3) {
				max-width: none;
			}
		}

		:deep(.customer-no-border-table .el-table--border, .el-table--group) {
			border: none;
		}

		.demo-pagination-block {
			margin-top: 16px;
			position: absolute;
			bottom: 32px;
			right: 32px;
		}

		.buttonFun {
			color: #2E83FC;
			font-size: 14px;
			margin-right: 8px;
		}

		.sircle {
			width: 6px;
			height: 6px;
			border-radius: 50%;

			display: inline-block;
			margin-bottom: 3px;
		}

		.blue {
			background-color: #2E83FC;
		}

		.green {
			background-color: #54B831;
		}

		.origin {
			background-color: #FFB929;
		}

		.origin_deep {
			background-color: #FF9458;
		}

		.red {
			background-color: #F46B5A
		}

		.bottomBox {
			padding: 16px;
			height: calc(100% - 48px);
		}
	}
</style>